package sunwin.yoms.web.comm.controllerAspect;

import jodd.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import sunwin.yoms.comm.YomsException;
import sunwin.yoms.service.comm.YomsDefaultData;
import sunwin.yoms.service.security.YomsUserDetails;
import sunwin.yoms.web.comm.YomsController;
import sunwin.yoms.web.comm.YomsControllerDefaultData;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by 田西泽 on 2015-8-26.
 * 鉴权
 */
@Component
public class AuthorityAspect {
    @Autowired
    private YomsControllerDefaultData defaultData;

    /**
     * 鉴权
     *
     * @param response
     * @param handler
     * @return
     * @throws IOException
     */
    public boolean authentication(HttpServletResponse response, HandlerMethod handler) throws IOException {
        YomsController yomsController = handler.getMethodAnnotation(YomsController.class);
        boolean isSuccess = false;

        if (yomsController == null || StringUtil.isBlank(yomsController.functionNo())) {
            isSuccess = true;
        } else {
            try {
                isSuccess = isAuthority(yomsController.functionNo());
            } catch (YomsException e) {
                response.setStatus(403);
                response.setCharacterEncoding("UTF-8");
                response.setContentType("text/html");
                response.getWriter().write("<html><head><title></title></head><body><script>window.location.href = \"/403.html\"</script></body></html>");
                isSuccess = false;
            }
        }
        return isSuccess;
    }

    private boolean isAuthority(String functionNo) throws YomsException {
        boolean isAuthority = false;
        YomsUserDetails userDetails = defaultData.getCurrentYomsUserDetails();

        if (userDetails != null) {
            if (userDetails.getUsername().equals(YomsDefaultData.AdminLoginName)) {
                isAuthority = true;
            } else {
                for (GrantedAuthority authority : userDetails.getAuthorities()) {
                    if (authority.getAuthority().equals(functionNo)) {
                        isAuthority = true;
                        break;
                    }
                }
            }
        }

        if (isAuthority) {
            return isAuthority;
        } else {
            throw YomsException.getInstance();
        }
    }
}
